package upload

import (
	"errors"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/spf13/viper"
	"io"
	"log"
	"mime/multipart"
	"os"
	"path/filepath"
)

// 多个文件上传 max文件最大个数(默认5) size每个文件最大(图片默认3MB，视频默认10MB)
func UpFile(files []*multipart.FileHeader, numMax, imgSize, videoSize int64) ([]string, error) {
	switch numMax {
	case 0:
		numMax = 5
	}
	switch imgSize {
	case 0:
		imgSize = 3
	}
	switch videoSize {
	case 0:
		videoSize = 10
	}
	if len(files) > int(numMax) {
		return nil, errors.New("最多不超过10个文件")
	}
	var urls []string
	for _, file := range files {
		ext := filepath.Ext(file.Filename)
		switch ext {
		case ".png", ".jpg", ".jpeg", ".gif":
			if file.Size > imgSize*1024*1024 {
				return nil, errors.New(fmt.Sprintf("图片大小不能大于%dMB", 5))
			}
		case ".mp4", ".mov":
			if file.Size > videoSize*1024*1024 {
				return nil, errors.New(fmt.Sprintf("视频大小不能大于%dMB", 20))
			}
		default:
			return nil, errors.New("只支持png、jpg、jpeg、gif、mp4、mov类型的文件")
		}

		filePath := fmt.Sprintf("./file/%s/%s", ext, file.Filename)
		err := saveUploadedFile(file, filePath)
		if err != nil {
			return nil, err
		}
		url := ossFileUp(file.Filename, filePath)

		urls = append(urls, url)
	}
	return urls, nil
}

func saveUploadedFile(file *multipart.FileHeader, dst string) error {
	src, err := file.Open()
	if err != nil {
		return err
	}
	defer src.Close()

	if err = os.MkdirAll(filepath.Dir(dst), 0750); err != nil {
		return err
	}

	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, src)
	return err
}

func ossFileUp(file, filePath string) string {
	client, err := oss.New(
		"https://oss-cn-"+viper.GetString("oss_connect_url")+".aliyuncs.com",
		viper.GetString("oss_id"),
		viper.GetString("oss_key"),
	)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}
	// 填写存储空间名称，例如examplebucket。
	bucketName := viper.GetString("bucket_name") // 请替换为实际的Bucket名称
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}
	// 依次填写Object的完整路径（例如exampledir/exampleobject.txt）和本地文件的完整路径（例如D:\\localpath\\examplefile.txt）。
	objectKey := viper.GetString("oss_storage_url") + file // 请替换为实际的对象Key
	localFilePath := filePath                              // 请替换为实际的本地文件路径
	err = bucket.PutObjectFromFile(objectKey, localFilePath)
	if err != nil {
		log.Fatalf("Failed to put object from file: %v", err)
	}
	log.Println("File uploaded successfully.")

	return viper.GetString("oss_get_url") + objectKey
}
